package com.android.djlmapp.activity.home.web.base;

import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.constraint.ConstraintLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.djlmapp.R;
import com.android.djlmapp.activity.home.web.BukaActivity;
import com.android.djlmapp.activity.home.web.MoreFunActivity;
import com.android.djlmapp.base.BaseActivity;
import com.android.djlmapp.js_interface.AbJsInterfaceCallBack;
import com.android.djlmapp.js_interface.BaseJsInterface;
import com.android.djlmapp.tools.ScreenUtil;
import com.android.djlmapp.tools.global.AndroidBug5497Workaround;
import com.android.djlmapp.view.WebView4Scroll;
import com.just.agentweb.AgentWeb;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

import static android.view.View.OVER_SCROLL_NEVER;
import static com.android.djlmapp.js_interface.BaseJsInterface.MORE_FUN_JS_SIGN_KEY;

/**
 * @Author wangziheng
 * @ProjectName djlm
 * @ClassName BaseWebActivity
 * @package com.android.djlmapp.activity.home.web
 * @data 2018/12/24 12:08
 * @Describe TODO  所有没有交互方法的纯展示的界面都可以直接使用这个类
 * 1> 可以通过{@link BaseJsInterface}添加一些公共的交互方法,进行拦截处理,
 * 目前暂不知道有哪些公共方法,比如说web主持的界面回退
 * 2> 可以通过{@link BaseWebViewClient}和{@link BaseWebChromeClient}
 * 拦截处理一些公共的web路径,比如说token过期
 * 3> 如果子类需要进行js交互,可以通过{@link #getJsInterface()} 设置js监听,
 * 通过{@link #getJsInterfaceKey()} 设置js交互的key;
 * (可以参考{@link BukaActivity}和{@link MoreFunActivity})
 * @Change
 */
public class BaseWebActivity extends BaseActivity {
    private Unbinder mUnbinder;
    @BindView(R.id.recharge_frame_refreshLayout)
    public SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.recharge_fragme_layout)
    FrameLayout mFrameLayout;
    @BindView(R.id.tv_name)
    public TextView mTitleTv;
    @BindView(R.id.iv_top_msg)
    ConstraintLayout mMsgLayout;
    public AgentWeb.PreAgentWeb mPreAgentWeb;
    /**
     * 当前界面要加载显示的路径key
     */
    public static final String PAGE_URL_KEY = "PAGE_URL_KEY";
    public String mPageUrl = null;
    /**
     * token过期  重新登录标识
     */
    public static final String TOKEN_DEAD_URL = "login_out";
    /**
     * 订单列表
     */
    public static final String TO_ORDER_LIST_URL = "Order/index";
    /**
     * 忘记密码界面
     */
    public static final String TO_FORGET_PSW_URL = "/get_paypwd";

    /**
     * 状态栏字体颜色是否为深色
     */
    public boolean isDrakFont = true;

    /**
     * 状态栏颜色
     */
    public int mStatusColor = Color.TRANSPARENT;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        windowStyle();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recharge_layout);
        mUnbinder = ButterKnife.bind(this);
        AndroidBug5497Workaround.assistActivity(this);
        fitsSystemWindows();
        initView();
    }

    public void windowStyle() {
        getWindow().requestFeature(Window.FEATURE_NO_TITLE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

            Window window = getWindow();

            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS

                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN

                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);

            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

            window.setStatusBarColor(mStatusColor);

        }
    }

    /**
     * 设置页面最外层布局 FitsSystemWindows 属性
     */
    private void fitsSystemWindows() {
        ViewGroup contentFrameLayout = findViewById(android.R.id.content);
        View parentView = contentFrameLayout.getChildAt(0);
        if (parentView != null) {
            //布局预留状态栏高度的 padding
            parentView.setFitsSystemWindows(true);
        }
    }

    @Override
    public void initImmersionBar(int color) {
        ScreenUtil.setStatusBarDarkFont(this, isDrakFont);
    }

    protected void setWebUrl(String url) {
        this.mPageUrl = url;
    }

    @Override
    protected void initView() {
        if (TextUtils.isEmpty(mPageUrl)) {
            mPageUrl = getIntent().getStringExtra(PAGE_URL_KEY);
        }

        mMsgLayout.setVisibility(View.GONE);
        mTitleTv.setText(null);
        mSwipeRefreshLayout.setEnabled(false);
        WebView webView = getScrollView();
        webView.setVerticalScrollBarEnabled(false);
        webView.setOverScrollMode(OVER_SCROLL_NEVER);
        mPreAgentWeb = AgentWeb.with(this)
                .setAgentWebParent(mFrameLayout, new RelativeLayout.LayoutParams(-1, -1))
                .useDefaultIndicator()
                .setWebView(webView)
                .setWebViewClient(getWebViewClient())
                .setWebChromeClient(getWebChromeClient())
                .setMainFrameErrorView(R.layout.agentweb_errorlayout, R.id.agentweb_re_query_data_layout)
                .createAgentWeb()
                .ready();
        new Handler().postDelayed(this::loadPage, 500);
    }

    /**
     * 如果想要界面不被刷新 可重写此方法 设置mSwipeRefreshLayout 为null
     * 参考{@link MoreFunActivity#getScrollView()}
     *
     * @return
     */
    public WebView getScrollView() {
        WebView4Scroll webView4Scroll = new WebView4Scroll(this, mSwipeRefreshLayout);
        return webView4Scroll;
    }

    /**
     * 加载界面
     */
    public void loadPage() {
        if (mPreAgentWeb != null) {
            mAgentWeb = mPreAgentWeb.go(mPageUrl);
            mAgentWeb.getAgentWebSettings().getWebSettings().setGeolocationEnabled(false);
            JsInterface();
        }
    }

    /**
     * 添加js交互
     */
    public void JsInterface() {
        String jsKey = getJsInterfaceKey();
        BaseJsInterface jsInterface = getJsInterface();
        if (!TextUtils.isEmpty(jsKey) && jsInterface != null) {
            mAgentWeb.getJsInterfaceHolder().addJavaObject(jsKey, jsInterface);
        }
    }

    /**
     * 设置js交互的key值
     * TODO 建议所有的web界面都重写这个方法
     *
     * @return
     */
    public String getJsInterfaceKey() {
        return MORE_FUN_JS_SIGN_KEY;
    }

    /**
     * 设置js交互的监听
     *
     * @return
     */
    public BaseJsInterface getJsInterface() {
        return new BaseJsInterface(this, new AbJsInterfaceCallBack() {
        }, mAgentWeb);
    }

    private WebViewClient mWebViewClient;
    private WebViewClient mDefaultWebViewClient = new BaseWebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (mSwipeRefreshLayout != null) {
                mSwipeRefreshLayout.setRefreshing(false);
            }
        }
    };

    /**
     * 设置webViewClient
     *
     * @param webViewClient
     */
    public void setWebViewClient(WebViewClient webViewClient) {
        mWebViewClient = webViewClient;
    }

    /**
     * 获取WebViewClient
     *
     * @return
     */
    private WebViewClient getWebViewClient() {
        if (mWebViewClient == null) {
            mWebViewClient = mDefaultWebViewClient;
        }
        return mWebViewClient;
    }

    private WebChromeClient mWebChromClient;
    private WebChromeClient mDefaultWebChromeClient = new BaseWebChromeClient() {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if(mTitleTv == null){
                return;
            }
            if (TextUtils.isEmpty(title) || title.contains("404")) {
                // 不是纯汉字
                mTitleTv.setText("网页无法打开");
            } else {
                mTitleTv.setText(title);
            }
        }
    };

    /**
     * 获取WebChromeClient
     *
     * @return
     */
    private WebChromeClient getWebChromeClient() {
        if (mWebChromClient == null) {
            mWebChromClient = mDefaultWebChromeClient;
        }
        return mWebChromClient;
    }

    /**
     * 设置WebChromeClient
     *
     * @param webChromeClient
     */
    public void setWebChromeClient(WebChromeClient webChromeClient) {
        mWebChromClient = webChromeClient;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onDestroy() {
        mUnbinder.unbind();
        // 如果先调用destroy()方法，则会命中if (isDestroyed()) return;这一行代码，需要先onDetachedFromWindow()，再
        // destory()
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mAgentWeb != null) {
                if (!mAgentWeb.back()) {
                    finish();
                }
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void btnBack() {
        if (mAgentWeb != null) {
            if (!mAgentWeb.back()) {
                finish();
            }
        } else {
            finish();
        }
    }
}
